package com.lbd.media.service.impl;

import java.util.Map;

import com.lbd.commons.exception.ControllerException;
import com.lbd.media.bean.Faq;
import com.lbd.media.dao.FaqRepository;
import com.lbd.media.service.FaqService;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.lbd.base.service.BaseServiceImpl;
import com.lbd.media.bean.Media;
import com.lbd.media.dao.MediaRepository;
import com.lbd.media.service.MediaService;

/**
 * Created by WangYajie on 2016/9/12.
 */
@Service
@Transactional
public class FaqServiceImpl extends BaseServiceImpl<Faq, FaqRepository> implements FaqService {
    private final Logger log = Logger.getLogger(this.getClass());
    @Autowired
    FaqRepository faqRepository;

    @Override
    public Specification<Faq> getSpecification(Faq media) {
        return null;
    }


    @Override
    public String buildJpql(Faq faq, Map<String, Object> parameter) {
        StringBuilder jpqlBuilder = new StringBuilder("  from  Faq t   ");
        if (faq != null) {
            if (StringUtils.isNotBlank(faq.getTitle())) {
                jpqlBuilder.append(" and  t.title like :title");
                parameter.put("title", "%" + faq.getTitle() + "%");
            }
            if (faq.getFaqType() != null && StringUtils.isNotEmpty(faq.getFaqType().getId())) {
                jpqlBuilder.append(" and  t.faqType.id = :faqTypeId");
                parameter.put("faqTypeId", faq.getFaqType().getId());
            }
            if (StringUtils.isNotBlank(faq.getState())) {
                jpqlBuilder.append(" and  t.state = :state");
                parameter.put("state", faq.getState());
            }
            jpqlBuilder.append(" order by createdDate desc ");
        }
        return jpqlBuilder.toString();
    }

    @Override
    public void update(Faq faq) {
        //校验已发布的不允许修改
        Faq old = faqRepository.findOne(faq.getId());
        if ("01".equals(old.getState())) {//TODO 获取数据字典、校验数据（如old)
            throw new ControllerException("发布后不允许修改");
        }
        //复制创建信息
        faq.setCreateUserId(old.getCreateUserId());
        faq.setCreatedDate(old.getCreatedDate());
        super.update(faq);
    }
}
